<template>
  <div>
    <h3>运动员进退队申请</h3>
    <div class="playerStatusApply">
      <vxe-toolbar>
        <template #buttons>
          <el-button type="success" icon="el-icon-plus" size="medium" @click="insertModal=true;modalTitle='运动员状态变更申请';edit=false">新增</el-button>
          <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索" @input="searchEvent"></vxe-input>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" border max-height="800" stripe highlight-hover-row highlight-current-row :loading="loading"
        :data="playerStatusApplyData">
        <vxe-table-column field="player" title="运动员" sortable width="110"></vxe-table-column>
        <vxe-table-column field="status" title="状态请求" sortable width="400">
          <template #default="{ row }">
            <div v-html="row.statusName"></div>
          </template>
        </vxe-table-column>
        <vxe-table-column field="result" title="审核过程" sortable width="100"></vxe-table-column>
        <vxe-table-column field="" title="操作">
          <template #default="{ row }">
            <el-link @click="editAction(row)" type="primary" v-if="row.resultId==2" icon="iconfont icon-xiugai">修改请求</el-link>
            <el-link @click="sendAction(row)" type="primary" icon="iconfont icon-fasong">发出请求</el-link>
            <el-link @click="repealAction(row)" type="primary" icon="iconfont icon-chexiao">撤销请求</el-link>
            <el-tooltip class="item" effect="dark" placement="top">
              <div slot="content" style="width: 200px;">
                <h4>{{playerProcess.playerInfo}}</h4>
                <p v-html="playerProcess.processInfo"></p>
              </div>
              <span @mouseenter="popoverShow(row)"><el-link icon="iconfont icon-xiangxixinxi1" type="primary">详细信息</el-link></span>
            </el-tooltip>
            <el-link @click="fileDowload(row)" type="primary" icon="iconfont icon-xiazai1">{{dict_status[row.status.split(',')[1]]}}申请表</el-link>
            <el-link @click="deleteAction(row)" type="primary" icon="el-icon-delete-solid">删除</el-link>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
    </div>
    <vxe-modal v-model="insertModal" :title="modalTitle">
      <template>
        <el-form inline-message ref="formData" :rules="rules" :model="formData" label-width="80px">
          <el-form-item label="运动员" prop="playerId">
            <el-select v-model="formData.playerId" @change="playerChange" filterable clearable placeholder="请选择" style="width: 100%;">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_player" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="当前状态">
            <el-select v-model="startStatus" :disabled="!edit" placeholder="请选择" style="width: 100%;">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_status" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目标状态">
            <el-cascader v-model="cascaderStatus" style="width: 100%;" :show-all-levels="false" :options="statusOptions" :props="{ expandTrigger: 'hover' }"></el-cascader>
          </el-form-item>
          <el-form-item v-show="!edit" label="执行时间">
            <el-date-picker
              v-model="formData.exeDate"
              align="right"
              type="date"
              placeholder="选择日期"
              style="width: 100%;"
              >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" size="small" @click="insertModal = false">取消</el-button>
            <el-button type="success" size="small" icon="el-icon-s-promotion" @click="insertSave">确定</el-button>
          </el-form-item>
        </el-form>
      </template>
    </vxe-modal>
    <vxe-modal v-model="printModal" title="预览" height="800" show-zoom resize width="600" show-footer>
      <template #default>
        <playerProcessStatusPrint id="myPrint" :currentPrint="currentPrint" />
      </template>
      <template #footer>
        <el-button @click="printEvent" type="primary" icon="el-icon-printer" size="mini">打印</el-button>
        <el-button @click="downloadWord" type="primary" icon="iconfont icon-word1" size="mini"> 导出word</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
  import {playerApplyDefault,player_status,playerApplyInsert,playerApplyUpdate,playerApplyDetail,process_playerInfo,playerApplyDelete} from "@/api/person.js"
  import {currentRolePlayer,player_process_result} from "@/api/dict.js"
  import playerProcessStatusPrint from "@/components/print/playerProcessStatusPrint.vue"
  import htmlDocx from 'html-docx-js/dist/html-docx';
  import saveAs from 'file-saver';
  export default {
    components: {
      playerProcessStatusPrint,
    },
    data() {
      return {
        visible: '',
        value: '',
        playerStatusApplyData: [],
        defaultPlayerStatusApplyData: [],
        dict_player: {},
        dict_result: {},
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        searchProps: [],
        dict_status: {
            "3": "预备",
            "4": "入队-试训",
            "1": "入队-转正",
            "6": "入队",
            "5": "上级单位集训试训",
            "2": "离队",
            "8": "在训"
        },
        insertModal: false,
        formData: {
          prioritySort: 10,
          currentStatusId: '',
          playerId: '',
          resultId: '',
          status: [],
          goalStatusId: '',
          exeDate: '',
        },
        statusOptions: [
          {
            value: '0',
            label: '入队/在训',
            children: [
              {
                value: '4',
                label: '试训',
              },
              {
                value: '1',
                label: '转正',
              },
              {
                value: '5',
                label: '上级单位集训试训',
              }
            ],
          },
          {
            value: '3',
            label: '预备',
            children: [
              {
                value: '3',
                label: '预备',
              },
            ],
          },
          {
            value: '2',
            label: '离队',
            children: [
              {
                value: '2',
                label: '离队',
              },
            ],
          }
        ],
        rules: {
          playerId: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
        },
        startStatus: '',
        cascaderStatus: ['0','4'],
        edit: false,
        modalTitle: '运动员状态变更',
        flowId: '',
        playerProcess: {playerInfo:'',processInfo:''},
        printModal: false,
        currentPrint: {},
        currentRow: {},
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.getPlayerStatusApply()
      })
    },
    methods: {
      deleteAction(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          playerApplyDelete({
            flowId: row.flowId
          }).then(res => {
            if (res.code === 200) {
              this.defaultPlayerStatusApplyData.forEach((item,index)=>{
              	if(item.flowId == row.flowId){
              	  this.defaultPlayerStatusApplyData.splice(index,1)
              	}
              })
              this.init_data(this.defaultPlayerStatusApplyData)
              this.findList()
              this.$message.success('删除成功！')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      downloadWord() {
        let name = this.currentPrint.name+this.currentPrint.title+'申请表'
        setTimeout(()=>{
          const divEl = document.getElementById('myPrint')
          this.page = `<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>${divEl.innerHTML}</body></html>`
          const converted = htmlDocx.asBlob(this.page);
          saveAs(converted, name+'.docx');
        },500)
      },
      printEvent() {
        const divEl = document.getElementById('myPrint')
        this.$XPrint({
          sheetName: '',
          content: divEl.innerHTML
        })
      },
      fileDowload(row) {
        process_playerInfo({playerId:row.playerId}).then(res=>{
          this.currentPrint = {}
          if(res.code === 200) {
            this.currentPrint = res.data
          }
          this.currentPrint.title = this.dict_status[row.status.split(',')[1]]
          this.printModal = true
        })
      },
      popoverShow(row) {
        playerApplyDetail({flowId:row.flowId,playerId:row.playerId}).then(res=>{
          if(res.code===200){
            this.playerProcess = res.data
            this.visible = row.flowId
          }else{
            this.playerProcess.playerInfo = '空'
          }
        })
      },
      editAction(row) {
        this.modalTitle = '运动员状态变更修改'
        this.edit = true
        this.flowId = row.flowId
        this.formData.playerId = row.playerId
        this.playerChange()
        this.insertModal = true
      },
      repealAction(row) {
        if(row.resultId == 1){
          this.$message.warning('请求尚未发出！')
        }else if(row.resultId == 3){
          this.$message.warning('已经批准的请求无法撤销.！')
        }else if(row.resultId == 5){
          this.$message.warning('已经驳回的请求无法撤销.！')
        }else{
          playerApplyUpdate({flowId:row.flowId,resultId:6}).then(res=>{
            if(res.code === 200) {
              this.$message.success('请求已撤销成功！')
              row.resultId = 6
              row.result = this.dict_result[row.resultId]
            }
          })
        }
      },
      sendAction(row) {
        if(row.resultId == 3){
          this.$message.warning('已经批准的请求无法再次请求.！')
        }else if(row.resultId == 5){
          this.$message.warning('已经驳回的请求无法再次请求.！')
        }else{
          playerApplyUpdate({flowId:row.flowId,resultId:2}).then(res=>{
            if(res.code === 200) {
              this.$message.success('请求已发出成功！')
              row.resultId = 2
              row.result = this.dict_result[row.resultId]
            }
          })
        }
      },
      insertSave() {
        this.$refs.formData.validate((valid) => {
          if (valid) {
            let data = {}
            data.prioritySort = this.formData.prioritySort++
            if(this.formData.playerId) data.playerId = this.formData.playerId
            data.status = this.startStatus+','+this.cascaderStatus[1]
            data.goalStatusId = this.cascaderStatus[1]
            data.currentStatusId = this.startStatus
            if(!this.edit){
              data.resultId = 1
              if(this.formData.exeDate) data.exeDate = this.$moment(this.formData.exeDate).format('YYYY-MM-DD') + ' 00:00:00'
              playerApplyInsert(data).then(res=>{
                if(res.code === 200){
                  this.$message.success('添加成功!')
                  this.getPlayerStatusApply()
                  this.insertModal = false
                }else{
                  this.$message.error(res.message)
                }
              })
            }else{
              data.resultId = 2
              data.flowId = this.flowId
              playerApplyUpdate(data).then(res=>{
                if(res.code === 200) {
                  this.$message.success('修改成功!')
                  this.insertModal = false
                  this.getPlayerStatusApply()
                }else{
                  this.$message.error(res.message)
                }
              })
            }

          }else{
            return false
          }
        })
      },
      playerChange(val) {
        player_status({playerId:val || this.formData.playerId}).then(res=>{
          if(res.code === 200 && res.data){
            this.startStatus = ''
            this.startStatus = res.data.playerStatusId
          }
        })
      },
      getPlayerStatusApply() {
        playerApplyDefault({defaultBeginDate:this.$moment().add(-3,'y').format('YYYY-MM-DD hh:mm:ss')}).then(res=>{
          if(res.code === 200 && res.data.length!=0) {
            this.init_data(res.data)
          }else{
            this.defaultPlayerStatusApplyData = []
          }
        }).then(()=>{
          this.findList()
        })
      },
      init_data(data) {
        if(data.length==0) return
        data.forEach(item=>{
          item.player = this.dict_player[item.playerId]
          item.result = this.dict_result[item.resultId]
          if(item.status){
            let statusArr = item.status.split(',')
            let arr = []
            statusArr.forEach(item=>{
              arr.push(this.dict_status[item])
            })
            item.statusName = arr.join(' <i class="iconfont icon-jiantou"></i> ')
          }
        })
        this.searchProps = Object.keys(data[0])
        this.defaultPlayerStatusApplyData = data
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
          player_process_result().then(res=>{
            this.dict_result = res
          })
          currentRolePlayer().then(res=>{
            this.dict_player = res
            resolve()
          })
        })
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultPlayerStatusApplyData.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.playerStatusApplyData = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
        } else {
          this.playerStatusApplyData = this.defaultPlayerStatusApplyData
          this.findList()
        }
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
        this.page.currentPage = 1
        this.page.pageSize = this.defaultDataList.length
        this.findList()
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.page.totalResult = this.defaultPlayerStatusApplyData.length
          this.playerStatusApplyData = this.defaultPlayerStatusApplyData.slice((this.page.currentPage - 1) * this.page
            .pageSize, this.page.currentPage * this.page.pageSize)
        }, 300)
      },
    },
  }
</script>

<style lang="scss" scoped>
  .playerStatusApply{
    background-color: #FFFFFF;
    padding: 10px;
    a{
      margin-right: 10px;
    }
  }
</style>
